<template>
  <Tab @goBack="goBack" :tabs="tabs" :current="current">
    <div slot="index">
      <el-form :inline="true" label-width="80px">
        <el-form-item label="任务名称">
          <el-input
            v-model="queryParams.jobName"
            placeholder="任务名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="方法名称">
          <el-input
            v-model="queryParams.invokeTarget"
            placeholder="方法名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select @keyup.enter.native="handleQuery" v-model="queryParams.status" placeholder="不限"
                     clearable
                     size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" v-hasPermi="['monitor:job:query']">搜索</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleInsert"  v-hasPermi="['monitor:job:add']">添加</el-button>
          <el-button type="primary" size="mini" icon="el-icon-document"  v-hasPermi="['monitor:job:log']" @click="handleLog('log')">日志</el-button>
        </el-form-item>


      </el-form>

      <el-table v-loading="loading" :data="postList">
        <el-table-column label="任务名称" align="center" prop="jobName" :show-tooltip-when-overflow="true"/>
        <el-table-column label="任务组名" align="center" prop="jobGroup" :show-tooltip-when-overflow="true"/>
        <el-table-column label="方法名称" align="center" prop="invokeTarget" :show-tooltip-when-overflow="true"/>
        <el-table-column label="方法参数" align="center" prop="methodParams" :show-tooltip-when-overflow="true"/>
        <el-table-column label="执行表达式" align="center" prop="cronExpression" :show-tooltip-when-overflow="true"/>
        <el-table-column label="任务状态" align="center" prop="status" :formatter="typeFormat"/>
        <el-table-column label="执行策略" align="center" prop="misfirePolicy" :formatter="typeFormat"/>
        <el-table-column label="创建时间" align="center" prop="createTime" :show-tooltip-when-overflow="true"/>
        <el-table-column label="备注" align="center" prop="remark" :show-tooltip-when-overflow="true"/>


        <el-table-column label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              v-if="scope.row.status==='1'"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['monitor:job:changeStatus']"
            >启用
            </el-button>

            <el-button
              size="mini"
              type="danger"
              v-if="scope.row.status==='0'"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['monitor:job:changeStatus']"
            >暂停
            </el-button>


            <el-button
              size="mini"
              type="success"
              @click="handleRun(scope.row)"
              v-hasPermi="['monitor:job:run']"
            >执行
            </el-button>

            <el-button
              size="mini"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['monitor:job:edit']"
            >编辑
            </el-button>

            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              v-hasPermi="['monitor:job:remove']"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="任务名称" prop="jobName">
            <el-input v-model="form.jobName" placeholder="请输入任务名称"/>
          </el-form-item>
          <el-form-item label="任务组名" prop="jobGroup">
            <el-input v-model="form.jobGroup" placeholder="请输入任务组名"/>
          </el-form-item>
          <el-form-item label="方法名称" prop="invokeTarget">
            <el-input v-model="form.invokeTarget" placeholder="请输入方法名称"/>
          </el-form-item>
          <el-form-item label="方法参数" prop="methodParams">
            <el-input v-model="form.methodParams" placeholder="请输入方法参数"/>
          </el-form-item>
          <el-form-item label="cron表达式" prop="cronExpression">
            <el-input v-model="form.cronExpression" placeholder="请输入cron表达式"/>
          </el-form-item>
          <el-form-item label="执行策略" prop="misfirePolicy">
            <el-radio-group v-model="form.misfirePolicy" size="small">
              <el-radio :label="item.dictValue" border v-for="item in misfirePolicyOptions">{{item.dictLabel}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status" size="small">
              <el-radio :label="item.dictValue" border v-for="item in statusOptions">{{item.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="5" placeholder="请输入备注"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="addLoading" @click.native.prevent="submitForm">
            <span v-if="!addLoading">提 交</span>
            <span v-else>提 交 中...</span>
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <div slot="log">
      <JobLog></JobLog>
    </div>
  </Tab>

</template>

<script>
  import Tab from "@/components/Tab";
  import {list, run, changeStatus, addJob, editJob, deleteJob} from "@/api/monitor/job";
  import JobLog from './log';

  export default {
    components: {Tab, JobLog},
    data() {
      return {
        runLoading: undefined,
        row: undefined,
        title: '',
        open: false,
        addLoading: false,
        loading: false,
        postList: [],
        statusOptions: [],
        misfirePolicyOptions: [
          {dictValue: '0', dictLabel: '默认'},
          {dictValue: '1', dictLabel: '立即执行'},
          {dictValue: '2', dictLabel: '执行一次'},
          {dictValue: '3', dictLabel: '放弃执行'}],
        current: 'index',
        tabs: [
          {index: 'index', name: ''}, {'index': 'log', name: '日志列表'},
        ],
        form: {
          jobName: undefined,
          jobGroup: undefined,
          invokeTarget: undefined,
          cronExpression: undefined,
          misfirePolicy: '1',
          status: "1",
          methodParams: undefined,
          remark: undefined
        },
        rules: {
          jobName: [
            {required: true, message: '请输入任务名称', trigger: 'blur'},
            {max: 50, message: '任务名称不能超过50个字符', trigger: 'blur'}
          ],
          jobGroup: [
            {required: true, message: '请输入任务组名', trigger: 'blur'},
            {max: 50, message: '任务组名不能超过50个字符', trigger: 'blur'}
          ],
          cronExpression: [
            {required: true, message: '请输入cron表达式', trigger: 'blur'},
            {max: 255, message: '任务组名不能超过255个字符', trigger: 'blur'}
          ],
          invokeTarget:[
            {required: true, message: '请输入方法名称', trigger: 'blur'},
            {max: 500, message: '任务组名不能超过500个字符', trigger: 'blur'}
          ],
        },
        total: 0,
        loadingInstance: undefined,
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          jobName: undefined,
          invokeTarget: undefined,
          status: undefined
        }
      }
    },
    created() {
      this.getDicts("sys_job_status").then(response => {
        this.statusOptions = response.data;
      });
      this.getList();
    },
    methods: {
      getList() {
        this.loading = true;
        list(this.queryDateRange(this.queryParams, this.daterange)).then(response => {
          this.postList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },

      typeFormat(row, column) {
        let option;
        if (column.property === 'status') {
          option = this.statusOptions;
        } else if (column.property === 'misfirePolicy') {
          option = this.misfirePolicyOptions;
        }
        return this.selectDictLabel(option, row[column.property]);
      },
      goBack(message) {
        this.current = 'index';
        this.getList();
      },
      handleRun(row) {
        this.runLoading = this.$loading({
          lock: true,
          text: "执行中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.1)"
        });
        run(row).then(res => {
          console.log(res);
          this.msgSuccess('执行成功');
          this.$nextTick(() => {
            this.runLoading.close();
          });
        });
      },
      handleChangeStatus(row) {
        this.runLoading = this.$loading({
          lock: true,
          text: "改变状态中...",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.1)"
        });
        if (row.status === '0') {
          row.status = '1';
        } else {
          row.status = '0';
        }
        changeStatus(row).then(res => {
          console.log(res);
          this.msgSuccess('操作成功');
          this.$nextTick(() => {
            this.runLoading.close();
          });
        });
      },
      handleInsert() {
        this.reset();
        this.title = '添加';
        this.open = true;
      },
      submitForm() {
        let _this = this;
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.addLoading = true;
            if (this.form.jobId) {
              editJob(this.form).then(response => {
                this.msgSuccess("编辑成功");
                this.open = false;
                this.getList();
              }).catch(function (e) {
                console.log(e);
                _this.addLoading = false;
              });
            } else {
              addJob(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(function (e) {
                console.log(e);
                _this.addLoading = false;
              });
            }
          }
        });
      },
      reset() {
        this.addLoading = false;
        this.form = {
          jobName: undefined,
          jobGroup: undefined,
          invokeTarget: undefined,
          cronExpression: undefined,
          misfirePolicy: '1',
          status: "1",
          methodParams: undefined,
          remark: undefined
        };
        this.resetForm("form");
      },
      cancel() {
        this.reset();
        this.open = false;
      },
      handleUpdate(row) {
        this.reset();
        this.form = {
          jobId: row.jobId,
          jobName: row.jobName,
          jobGroup: row.jobGroup,
          invokeTarget: row.invokeTarget,
          cronExpression: row.cronExpression,
          misfirePolicy: row.misfirePolicy,
          status: row.status,
          methodParams: row.methodParams,
          remark: row.remark
        };
        this.title = '编辑';
        this.open = true;
      },
      handleDelete(row) {
        let _this = this;
        this.$confirm(`确定要删除任务名称为[${row.jobName}],任务组名称为[${row.jobGroup}]的记录?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          deleteJob(row.jobId).then(response => {
            _this.msgSuccess("删除成功");
            _this.getList();
          });
        }).catch(function (e) {
          console.log(e);
        });
      },
      handleLog(str) {
        this.current = str;
      }
    }
  }
</script>

<style>

</style>
